package ccnt.pvc.scudwaremobile.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import ccnt.pvc.scudwaremobile.R;
import ccnt.pvc.scudwaremobile.coop.ScudwareUPnPServiceImpl;
import ccnt.pvc.scudwaremobile.service.ApkService;
import ccnt.pvc.scudwaremobile.service.MainService;
import ccnt.pvc.scudwaremobile.service.ServiceManager;
import ccnt.pvc.scudwaremobile.utils.Constants.PreferenceKeys;
import ccnt.pvc.scudwaremobile.utils.Constants.PreferenceNames;

public class MainActivity extends Activity implements OnClickListener{

	Button btnCoop;
	Button btnPlugin;
	Button btnService;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		initView();
		initService();
	}

	private void initView() {
		btnCoop = (Button)findViewById(R.id.btnCoop);
		btnCoop.setOnClickListener(this);
		
		btnPlugin = (Button)findViewById(R.id.btnPlugin);
		btnPlugin.setOnClickListener(this);
		
		btnService = (Button)findViewById(R.id.btnService);
		btnService.setOnClickListener(this);
	}
	
	private void initService() {
		startService(new Intent(MainActivity.this, ScudwareUPnPServiceImpl.class));
		startService(new Intent(MainActivity.this, ApkService.class));
		startService(new Intent(MainActivity.this, ServiceManager.class));
		startService(new Intent(MainActivity.this, MainService.class));
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getTitle().equals(getString(R.string.menu_logout))) {
			logout();
			return true;
		}
		return false;
	}
	
	private void logout() {
		SharedPreferences preference = getSharedPreferences(
				PreferenceNames.LOGIN_PREFERENCE, MODE_PRIVATE);
		preference.edit().putBoolean(PreferenceKeys.IS_LOGIN, false).commit();
		startActivity(new Intent(MainActivity.this, LoginActivity.class));
		this.finish();
	}

	@Override
	public void onClick(View view) {
		int id = view.getId();
		switch(id) {
		case R.id.btnCoop:
			startActivity(new Intent(MainActivity.this, CoopActivity.class));
			break;
		case R.id.btnPlugin:
			startActivity(new Intent(MainActivity.this, ApkListActivity.class));
			break;
		case R.id.btnService:
			startActivity(new Intent(MainActivity.this, ServiceListActivity.class));
			break;
		}
	}

}
